import { StyleSheet, Text, View, Image, TextInput } from 'react-native';
import React, { useCallback, useEffect, useState } from 'react';
import axios from 'axios';
import { List, Stepper, Toast, Checkbox, Button } from '@ant-design/react-native';
import { router, useFocusEffect } from 'expo-router';
import AsyncStorage from '@react-native-async-storage/async-storage';


export default function cart() {
  const [shoplist, setShoplist] = useState([]);
  const [flag, setFlag] = useState(false)
  const [allPrice, setAllPrice] = useState(0)
  const [checkall, setCheckall] = useState(false)
  const [checknum, setChecknum] = useState(0)
  const getShoplist = async () => {
    const { data: { data, code } } = await axios.get("http://192.168.13.227:3000/shoplist");
    setShoplist(data);
    setAllPrice(data.filter((item: any) => item.flag === true).reduce((acc: any, cur: any) => acc + cur.lid.price * cur.num, 0))
    setCheckall(data.every((item: any) => item.flag === true))
    setChecknum(data.filter((item: any) => item.flag === true).length)
  };
  const onChanges = (e: { target: { checked: boolean } }, _id: string) => {
    console.log(`checked = ${e.target.checked}`)
    axios.put('http://192.168.13.227:3000/upshoplist', { _id, flag: e.target.checked })
      .then(() => {
        Toast.info('修改成功');
        getShoplist();
      })
      .catch((err) => {
        console.log(err);
      });
  }
  const onChangeAll = (e: { target: { checked: boolean } }) => {
    console.log(`checked = ${e.target.checked}`)

    axios.put('http://192.168.13.227:3000/upcheckall', { flag: e.target.checked })
      .then(() => {
        Toast.info('修改成功');
        getShoplist();
      })
      .catch((err) => {
        console.log(err);
      });
  }
  const deleteShoplist = async () => {
    const { data: { code } } = await axios.delete('http://192.168.13.227:3000/delshoplist', {
      params: {
        _id: shoplist.filter((item: any) => item.flag === true).map((item: any) => item._id)
      }
    });
    if (code === 200) {
      getShoplist();
    }

  }
  const [info, setInfo] = useState({
    user: '请登录',
    phone: '',
    image: 'https://img0.baidu.com/it/u=1240274933,2284862568&fm=253&fmt=auto&app=138&f=PNG?w=180&h=180',
    sex: ''
  })
  // useFocusEffect(
  //   useCallback(() => {
      
  //   }, []) // 依赖数组为空，确保只在组件挂载时运行一次
  // );

  useEffect(() => {
    getShoplist();
    const fetchUserInfo = async () => {
      try {
        const res = await AsyncStorage.getItem('userInfo');
        if (res) {
          setInfo(JSON.parse(res));
          getShoplist();
        } else {
          router.push('/LoginModel/login')
        }
      } catch (error) {
        console.error('Error fetching user info:', error);
      }
    };
    fetchUserInfo();
  }, []);

  return (
    <View style={styles.container}>
      <Button type='ghost' size='small' style={styles.editBtn} onPress={() => { setFlag(!flag) }}>{flag ? "完成" : "编辑"}</Button>
      {shoplist.map((item: any) => (
        <View style={styles.productDetails} key={item._id}>
          <Checkbox checked={item.flag} onChange={(e) => { onChanges(e, item._id) }} ></Checkbox>
          <Image source={{ uri: item.lid.img[0] }} style={styles.productImage} />
          <View style={styles.productTextContainer}>
            <Text style={styles.productName}>{item.lid.name}</Text>
            <Text style={styles.price}>
              <Text style={styles.currencySymbol}>¥{item.lid.price}</Text>
            </Text>
            <Stepper
              min={1}
              defaultValue={item.num}
              onChange={(value) => {
                console.log(value);
                axios.put("http://192.168.13.227:3000/upshoplist", { _id: item._id, num: value })
                  .then(() => {
                    Toast.info('修改成功');
                    getShoplist();
                  })
                  .catch((err) => {
                    console.log(err);
                  });
              }}
              style={styles.stepper}
            />
          </View>
        </View>
      ))}
      <View style={styles.buttonsContainer}>
        <Text style={styles.selectAll}>
          <Checkbox checked={checkall} onChange={(e) => { onChangeAll(e) }} ></Checkbox>
          全选
        </Text>
        <Text style={styles.total}>合计:¥ {allPrice}</Text>
        <View style={styles.checkoutBtn}>
          {
            flag ?
              <>
                {
                  checknum === 0 ? <Button size='small' type='warning' disabled>
                    删除
                  </Button> : <Button size='small' type='warning' onPress={deleteShoplist}>
                    删除
                  </Button>
                }
              </>

              : <>
                {
                  checknum === 0 ? <Button size='small' type='primary' disabled>
                    结算
                  </Button> : <Button size='small' type='primary'>
                    结算
                  </Button>
                }
              </>
          }

        </View>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 15,
  },
  title: {
    fontSize: 22,
    fontWeight: 'bold',
    marginTop: 10,
    marginBottom: 15,
  },
  addressInfo: {
    marginBottom: 10,
    alignItems: 'center',
  },
  productDetails: {
    marginBottom: 15,
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: "white",
    padding: 5,
    borderRadius: 5,
  },
  productImage: {
    width: 80,
    height: 80,
    marginRight: 10,
    borderRadius: 5,
  },
  productTextContainer: {
    flex: 1,
    justifyContent: 'space-between',
  },
  productName: {
    fontSize: 16,
    fontWeight: 'bold',
    marginBottom: 5,
  },
  price: {
    fontSize: 16,
    fontWeight: 'bold',
    alignItems: 'center',
    justifyContent: 'flex-start',
    color: '#333',
  },
  currencySymbol: {
    fontSize: 12,
    fontWeight: 'bold',
    marginRight: 3,
  },
  buttonsContainer: {
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
  selectAll: {
    fontSize: 14,
    color: '#555',
    alignItems: 'center',
    justifyContent: 'center',
  },
  total: {
    fontSize: 14,
    color: '#555',
    alignItems: 'center',
    justifyContent: 'center',
  },
  checkoutBtn: {
    // backgroundColor: '#007AFF',
    padding: 8,
    borderRadius: 4,
    alignItems: 'center',
    justifyContent: 'center',

  },
  checkoutText: {
    color: 'white',
    fontSize: 10,
    textAlign: 'center',
    alignItems: 'center',
    justifyContent: 'center',
  },
  checkoutTextButton: {
    width: 80,
    height: 40,
    backgroundColor: '#007AFF',
    fontSize: 5,
    borderRadius: 8,
    paddingVertical: 12,
    paddingHorizontal: 20,
    alignItems: 'center',
    justifyContent: 'center',
    textTransform: 'uppercase',
  },
  stepper: {
    width: 80,
    height: 30,
    borderRadius: 5,
    backgroundColor: '#f5f5f5',
    justifyContent: 'center',
    alignItems: 'center',
  },
  editBtn: {
    width: 50,
    height: 30,
  }
});